package zct.proj.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.util.Log;

public class PlaySound implements Runnable {

	private boolean run = true;
	private MediaPlayer mp = new MediaPlayer();
	private boolean playing = false;
	private ArrayList<String> playList = new ArrayList<String>();
	
	public void end() {
		if (mp.isPlaying()) {
			mp.stop();
		}
		mp = null;
		run = false;
	}
	
	@Override
	public void run() {
		CommUtil.writeLog("播音线程启动。");
		mp.setOnCompletionListener(new OnCompletionListener() {
			
			@Override
			public void onCompletion(MediaPlayer mp) {
				playing = false;
//				playSound();
			}
		});
		
		while (run && !Thread.interrupted()) {
			if (!playing && playList.size() > 0) {
				playSound();
			}
			
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		CommUtil.writeLog("播音线程终止。");
	}
	
	public void addTask(String playString) {
		
		String path = "Female";
		if (playString.startsWith("SX")) {
			path = "Male";
		}
		if (playString != null) {
			String[] sounds = playString.split(",");
			for (String sound : sounds) {
				if (sound != null && sound.length() > 0) {
					playList.add(path + "/" + sound + ".wav");
				}
			}
			// 添加空行，代表本段结束
			playList.add(null);
		}
	}

	private void playSound() {
//		Log.v("play", "play sound called and now is " + (playing ? "1": "0"));
		if (mp == null) {
			mp = new MediaPlayer();
		}
		if (!playing && playList.size() > 0) {
//			mp = new MediaPlayer();
			String file = playList.get(0);
			if (file == null) {
				playList.remove(0);
				if (playList.size() > 0) {
					try {
//						Log.v("play", "sleep 1000ms");
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
			
			if (playList.size() > 0) {
				try {
					playing = true;
					mp.reset();
					String soundFile = IniParser.getStationSoundPath() + "/" + playList.get(0);
					// 专用音库不区分男女声，替换所有男女声标志
					soundFile = soundFile.replaceAll("Female/", "").replaceAll("Male/", "");
					File sfile = new File(soundFile);
					if (!sfile.exists()) {
						soundFile = IniParser.getSoundRootPath() + "/" + playList.get(0);
						sfile = new File(soundFile);
						if (!sfile.exists()) {
							Log.i("play sound:", "Sound file not found:"+soundFile);
							playing = false;
							playList.remove(0);
//							playSound();
							return;
						}
					}
					mp.setDataSource(soundFile);
					mp.prepare();
					mp.start();
					playList.remove(0);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
